package softtech.apps.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import softtech.apps.dangtinraovat.R;
import softtech.apps.model.Conversation;

public class ConversationAdapter extends ArrayAdapter<Conversation> {

	private List<Conversation> chatMessageList = new ArrayList<Conversation>();
	@Override
	public void add(Conversation object) {
		chatMessageList.add(object);
		super.add(object);
	}

	public ConversationAdapter(Context context, int textViewResourceId) {
		super(context, textViewResourceId);
	}

	public int getCount() {
		return this.chatMessageList.size();
	}

	public Conversation getItem(int index) {
		return this.chatMessageList.get(index);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ConversationViewHolder viewHolder;
		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.conversation_item, parent, false);
			
			 viewHolder = new ConversationViewHolder();
			 viewHolder.chatText = (TextView) row.findViewById(R.id.singleMessage);
			 viewHolder.singleMessageContainer = (RelativeLayout) row.findViewById(R.id.singleMessageContainer);
	         row.setTag(viewHolder);
		}else {
            viewHolder = (ConversationViewHolder)row.getTag();
        }
		
		Conversation chatMessageObj = getItem(position);
		Log.d("MES","Thong diep se hien thi ben nao ="+chatMessageObj.isLeft());
		viewHolder.chatText.setText(chatMessageObj.message);
		viewHolder.chatText.setBackgroundResource(chatMessageObj.isLeft() == 1 ? R.drawable.bubble_a : R.drawable.bubble_b);
		
		
		if(chatMessageObj.isLeft() == 0){
			RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
			param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			viewHolder.chatText.setLayoutParams(param);
		}else{
			RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
			param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			viewHolder.chatText.setLayoutParams(param);
		}
		return row;
	}

    static class ConversationViewHolder {
        TextView chatText;
        RelativeLayout singleMessageContainer;
    }
    
	public Bitmap decodeToBitmap(byte[] decodedByte) {
		return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
	}

}